import React, { Component } from "react";
import styles from "./index.module.css";
import axios from "axios";
export default class Search extends Component {
  iptRef = React.createRef();
  handleSearch = () => {
    if (this.props.isFirstLoad) {
      this.props.updateAppState({ isFirstLoad: false });
    }
    const { value: keyword } = this.iptRef.current;
    this.props.updateAppState({ loading: true, list: [] });
    axios
      .get(`/api1/search/users?q=${keyword}`)
      .then(res => {
        const list = res.data.items;
        this.props.updateAppState({ list });
      })
      .catch(error => {
        this.props.updateAppState({ err: error.message });
        console.error(error);
      })
      .finally(() => {
        this.props.updateAppState({ loading: false });
      });
  };
  render() {
    return (
      <div className={styles.search}>
        <input
          ref={this.iptRef}
          className={styles["search-ipt"]}
          type="text"
          placeholder="输入名字搜索gitHub用户"
        />
        <button className={styles["search-btn"]} onClick={this.handleSearch}>
          搜索
        </button>
      </div>
    );
  }
}
